package org.esisar.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.esisar.model.Model;
import org.esisar.model.Sizes;

public class SizesStatementCreator implements StatementCreator{
private PreparedStatement preparedStatement;
	
	@Override
	public PreparedStatement addStatement(Connection connection, Model model) throws SQLException {
		
		Sizes size = modelToSize(model);
			
		preparedStatement = connection.prepareStatement("INSERT INTO sizes (idSize,price,format) VALUES(sizes_sequence.nextval,?,?)");

		fillModel(size);
	
		return preparedStatement;
		
	}

	@Override
	public PreparedStatement deleteStatement(Connection connection, List<Long> keys) throws SQLException {

		preparedStatement = connection.prepareStatement("DELETE FROM sizes WHERE idSize=?");

		preparedStatement.setLong(1, keys.get(0));
				
		return preparedStatement;
	}

	@Override
	public PreparedStatement updateStatement(Connection connection, Model model)
			throws SQLException {
		
		Sizes size = modelToSize(model);
		
		preparedStatement = connection.prepareStatement("UPDATE sizes SET price = ?,format = ? WHERE idSize = ?");

		fillModel(size);
		preparedStatement.setLong(3, size.getIdSize());
		
		return preparedStatement;
	}

	private void fillModel(Sizes size) throws SQLException {
		preparedStatement.setFloat(1, size.getPrice());
		preparedStatement.setString(2, size.getFormat());
	}

	private Sizes modelToSize(Model model) {
		Sizes size;
		
		if (model instanceof Sizes){
			size = (Sizes) model;
		}else{
			throw new ClassCastException("Bad object instance");
		}
		return size;
	}

	@Override
	public PreparedStatement readStatement(Connection connection, String field,
			String value) throws SQLException {		
		preparedStatement = connection.prepareStatement("SELECT * FROM sizes WHERE " + field + " LIKE ? ");

		preparedStatement.setString(1, value);
		
		return preparedStatement;
	}

	@Override
	public Model fillModel(ResultSet rs) throws SQLException {
		String idSize = rs.getString("idSize");
		float price = rs.getFloat("price");
		String format = rs.getString("format");
		
		Sizes size = new Sizes(price,format);
		size.setIdSize(Long.parseLong(idSize));
		
		return size;
			
	}
}
